package com.wyy.mall.tiny.service.impl;

import com.wyy.mall.tiny.nosql.mongodb.document.MemberReadHistory;
import com.wyy.mall.tiny.nosql.mongodb.repository.MemberReadHistoryRepository;
import com.wyy.mall.tiny.service.MemberReadHistoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 会员浏览记录管理Service实现类
 * created by 伍猷煜 on 2021/5/20 21:32 星期四
 */
@Service
public class MemberReadHistoryServiceImpl implements MemberReadHistoryService {

    @Autowired
    private MemberReadHistoryRepository mMemberReadHistoryRepository;

    @Override
    public int create(MemberReadHistory memberReadHistory) {
        // 创建的时候，文档ID设置为空，到时会自动生成ID
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        mMemberReadHistoryRepository.save(memberReadHistory);
        return 1;
    }

    @Override
    public int delete(List<String> ids) {
        // List<MemberReadHistory> deleteList = new ArrayList<>();
        // for (String id : ids) {
        //     MemberReadHistory m = new MemberReadHistory();
        //     m.setId(id);
        //     deleteList.add(m);
        // }
        // // 这里就没有返回值，代表有没有删除成功？
        // mMemberReadHistoryRepository.deleteAll(deleteList);
        // return ids.size();
        // 这里暂时没有很好的办法，只能是先判断id是否存在，或者先查询id对象的文档，再删除
        List<MemberReadHistory> deleteList = new ArrayList<>();
        int success = 0;
        for (String id : ids) {
            if (mMemberReadHistoryRepository.existsById(id)) {
                success++;
                mMemberReadHistoryRepository.deleteById(id);
            }
        }
        return success;
    }

    @Override
    public List<MemberReadHistory> list(Long memberId) {
        return mMemberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(memberId);
    }
}
